package com.lznAdmin.security.authentication.session;

import cn.hutool.core.util.StrUtil;
import com.lznAdmin.security.config.CustomAuthenticationFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import java.io.IOException;

/**
 * @program: lzn-manage-parent
 * @description: 当达到最大session数时，调用的实现
 * @author: lzn
 * @create: 2021-07-29 00:22
 **/
@Component
public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    @Autowired
    CustomAuthenticationFailHandler customAuthenticationFailHandler;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        // 退出的用户
        UserDetails userDetails = (UserDetails) event.getSessionInformation().getPrincipal();

        AuthenticationServiceException exception =
                new AuthenticationServiceException(StrUtil.format(("{}用户在另外一台电脑登录，您已被下线"),
                        userDetails.getUsername()));
        try {
            event.getRequest().setAttribute("toAuthentication", true);
            customAuthenticationFailHandler.onAuthenticationFailure(event.getRequest(), event.getResponse(), exception);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
